<template>
  <!-- 品牌添加 -->
  <div class="updateBrand">
    <!-- 表单 -->
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
    >
      <el-form-item label="品牌名称" prop="name">
        <el-input v-model="ruleForm.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="是否首字母">
        <el-input v-model="ruleForm.firstLetter" autocomplete="off" />
      </el-form-item>
      <el-form-item label="品牌LOGO" prop="logo">
        <!-- 上传图片 -->
        <el-upload
          ref="upload"
          v-model:file-list="fileListOne"
          :auto-upload="false"
          :limit="1"
          :on-exceed="handleExceed"
          :on-change="handleChange"
          list-type="picture"
          :on-remove="handleRemove"
        >
          <el-button type="primary">点击上传</el-button>
          <template #tip>
            <div class="el-upload__tip">只能上传jpg/png文件，且不超过10Mb</div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="品牌专区大图">
        <!-- 上传图片 -->
        <el-upload
          ref="uploada"
          v-model:file-list="fileListTwo"
          :auto-upload="false"
          :limit="1"
          :on-exceed="handleExceeda"
          :on-change="handleChangea"
          list-type="picture"
        >
          <el-button type="primary">点击上传</el-button>
          <template #tip>
            <div class="el-upload__tip">只能上传jpg/png文件，且不超过10Mb</div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="品牌故事">
        <!-- 上传图片 -->
        <el-input
          v-model.number="ruleForm.brandStory"
          class="textarea"
          type="textarea"
          placeholder="请输入内容"
        />
      </el-form-item>
      <el-form-item label="排序">
        <!-- 上传图片 -->
        <el-input v-model.number="ruleForm.sort" />
      </el-form-item>
      <el-form-item label="是否显示">
        <el-radio-group v-model="ruleForm.showStatus" class="ml-4">
          <el-radio :label="1" size="small">是</el-radio>
          <el-radio :label="0" size="small">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="品牌制造商">
        <el-radio-group v-model="ruleForm.factoryStatus" class="ml-4">
          <el-radio :label="1" size="small">是</el-radio>
          <el-radio :label="0" size="small">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)"
          >提交</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, FormInstance } from "element-plus";
import { reactive, ref } from "vue";
import * as http from "@/request/http";
// import { useRouter } from "vue-router";
// 引入类型
import type {
  UploadInstance,
  UploadProps,
  UploadUserFile,
  UploadRawFile,
} from "element-plus";
// const router = useRouter();
const fileListOne = ref<UploadUserFile[]>([
  {
    name: "food.jpeg",
    url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
  },
]);
const fileListTwo = ref<UploadUserFile[]>([
  {
    name: "food.jpeg",
    url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
  },
]);
const handleExceed: UploadProps["onExceed"] = (files) => {
  upload.value!.clearFiles(); // clearFiles 清空已上传的文件列表（该方法不支持在 before-upload 中调用）
  const file = files[0] as UploadRawFile; // 拿到最新上传的文件
  upload.value!.handleStart(file); // handleStart 手动选择文件
};
// logo
// 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
const handleChange: UploadProps["onChange"] = async (uploadFile) => {
  // const backupFileList = [...fileList.value]; // 备份已上传的文件，在新上传文件不符合要求的情况下，可以将以上传的文件重新赋值给文件列表
  console.log(uploadFile);
  const { type, size } = uploadFile.raw as UploadRawFile;
  const validTypes = ["image/jpeg", "image/jpg", "image/png"];
  const maxSize = 10 * 1024 * 1024; // 单位byte
  if (!validTypes.includes(type) || size > maxSize) {
    ElMessage.error("只能上传jpg/png文件，且不超过10Mb!");
    // fileList.value = backupFileList; // 在新上传文件不符合要求的情况下，可以将以上传的文件重新赋值给文件列表
    return;
  }
  // 将文件通过接口给后端换取文件链接地址
  const formData = new FormData();
  formData.append("file", uploadFile.raw as UploadRawFile);
  http.brand.minioUpload(formData).then((res) => {
    ruleForm.logo = res.data.url;
  });
};
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
  ruleForm.logo = "";
};

// 品牌专区大图
// 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
const handleChangea: UploadProps["onChange"] = async (uploadFile) => {
  // const backupFileList = [...fileList.value]; // 备份已上传的文件，在新上传文件不符合要求的情况下，可以将以上传的文件重新赋值给文件列表
  console.log(uploadFile);
  const { type, size } = uploadFile.raw as UploadRawFile;
  const validTypes = ["image/jpeg", "image/jpg", "image/png"];
  const maxSize = 10 * 1024 * 1024; // 单位byte
  if (!validTypes.includes(type) || size > maxSize) {
    ElMessage.error("只能上传jpg/png文件，且不超过10Mb!");
    // fileList.value = backupFileList; // 在新上传文件不符合要求的情况下，可以将以上传的文件重新赋值给文件列表
    return;
  }
  // 将文件通过接口给后端换取文件链接地址
  const formData = new FormData();
  formData.append("file", uploadFile.raw as UploadRawFile);
  http.brand.minioUpload(formData).then((res) => {
    ruleForm.bigPic = res.data.url;
    // console.log(res.name, res.url);
  });
};
const handleExceeda: UploadProps["onExceed"] = (files) => {
  uploada.value!.clearFiles(); // clearFiles 清空已上传的文件列表（该方法不支持在 before-upload 中调用）
  const file = files[0] as UploadRawFile; // 拿到最新上传的文件
  uploada.value!.handleStart(file); // handleStart 手动选择文件
};
const upload = ref<UploadInstance>(); // 获取el-upload的DOM
const uploada = ref<UploadInstance>(); // 获取el-upload的DOM
// 校验
const rules = reactive({
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  logo: [{ required: true, message: "请上传logo", trigger: "blur" }],
});
const ruleFormRef = ref<FormInstance>();
let ruleForm = reactive<brandCreateParams>({
  bigPic: "", //品牌大图
  brandStory: "", //品牌故事
  factoryStatus: 0, //是否为厂家制造商
  firstLetter: "", //是否首字母
  logo: "", //品牌LOGO
  name: "", //品牌名称
  showStatus: 0, //是否显示
  sort: 0, //排序
});
interface brandCreateParams {
  bigPic: string;
  brandStory: string;
  factoryStatus: number;
  firstLetter: string;
  logo: string;
  name: string;
  showStatus: number;
  sort: number;
}
// 提交按钮
const submitForm = (formEl: any) => {
  console.log(formEl);
  if (!formEl) return;
  formEl.validate((vaild: any) => {
    if (vaild) {
      http.brand.brandCreate(ruleForm).then((res) => {
        console.log(res);
        if (res.data.code == 200) {
          router.push("/pms/brand");
        }
        //   console.log("submit!");
      });
    }
  });
};
</script>

<style lang="less" scoped>
.addBrand {
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.el-form) {
  margin: auto;
  width: 700px;
  border: 1px solid #eee;
  padding: 30px;
}

:deep(.el-input__wrapper, #el-id-9924-19) {
  flex-grow: 0;
  width: 400px;
}
.textarea {
  width: 420px;
}
</style>
